﻿window.onload = function () {
    window.ui = SwaggerUIBundle({
        urls: [{"name":"default","url":"api/default.json"},{"name":"分组一","url":"api/分组一.json"},{"name":"自定义分组","url":"api/自定义分组.json"}],
        dom_id: '#swagger-ui',
        deepLinking: true,
        presets: [
            SwaggerUIBundle.presets.apis,
            SwaggerUIStandalonePreset
        ],
        plugins: [
            SwaggerUIBundle.plugins.DownloadUrl
        ],
        layout: "StandaloneLayout",
        onComplete: function () {
            var keyName = "token";
            if (keyName == null || keyName == "") {
                return;
            }
            var keyVal = window.localStorage.getItem(keyName);
            if (keyVal != null && keyVal != "") {
                window.ui.preauthorizeApiKey(keyName, keyVal);
            }
            document.getElementsByClassName('auth-wrapper')[0].addEventListener('click', function (ev) {
                var target = ev.target || ev.srcElement;
                if (target.nodeName.toLowerCase() == 'button') {
                    if (target.children.length > 0) {
                        return;
                    }
                    var btnTxt = target.innerText;
                    if (btnTxt == "Authorize") {
                        var rootDiv = document.getElementsByClassName("auth-container")[0];
                        var formDiv = rootDiv.children[0];
                        var wrapDiv = formDiv.children[0];
                        if (keyName != 'Authorization Bearer') {
                            wrapDiv = wrapDiv.children[0];
                        }
                        var input = wrapDiv.lastChild.children[1].children[0];
                        var inputVal = input.value;
                        if (inputVal == "") {
                            return;
                        }
                        window.localStorage.setItem(keyName, inputVal);
                    }
                    else if (btnTxt == "Logout") {
                        window.localStorage.removeItem(keyName);
                    }
                }
            });
        },
        responseInterceptor: function (res) {
            var keyName = "token";
            if (keyName != null && keyName != "") {
                try {
                    var url = res.url.split('?')[0].toLowerCase();
                    if (url.endsWith('@@loginUrl'.toLocaleLowerCase())) {
                        var obj = res.obj;
                        var val = obj;
                        if (val != null && val != "" && val != undefined) {
                            window.localStorage.setItem(keyName, val);
                            window.ui.preauthorizeApiKey(keyName, val);
                        }
                    }
                } catch { }
            }
            return res;
        }
    });
};